from django.core.paginator import Paginator
from django.http import HttpResponse
from django.views.decorators.http import require_POST, require_GET
from utils.customer_util import CustomerUtil
from utils.response_code import ResponseCode

from .models import Course


@require_POST
def course_page(request):
    """课程分页信息"""
    param = CustomerUtil.get_request_params(request)
    page = param.get('page', 1)
    size = param.get('size', 5)
    courses = Course.objects.all()
    paginator = Paginator(courses, size)
    total = paginator.count
    current_page = paginator.page(page)
    table_data = list(current_page.object_list.values())
    # [{},{},{}]
    for course in table_data:
        course['course_state'] = "正常" if course["course_state"] == 1 else "停课"

    return CustomerUtil.response_json({
        'total': total,
        'code': ResponseCode.BUSINESS_SUCCESS,
        "table_data": table_data
    })


@require_POST
def course_insert_edit(request):
    form = CustomerUtil.get_request_params(request)
    try:
        if form.get(id):
            Course.objects.filter(id=id).update(**form)
        else:
            Course(**form).save()
        response = {
            'code': ResponseCode.BUSINESS_SUCCESS,
            'message': "操作成功"
        }
    except Exception as e:
        response = {
            'code': ResponseCode.BUSINESS_ERROR,
            'message': str(e)
        }

    return CustomerUtil.response_json(response)


@require_GET
def course_delete(request, id):
    try:
        Course.objects.filter(id=id).delete()
        response = {
            'code': ResponseCode.BUSINESS_SUCCESS,
            'message': "删除成功"
        }
    except Exception as e:
        response = {
            'code': ResponseCode.BUSINESS_ERROR,
            'message': str(e)
        }

    return CustomerUtil.response_json(response)


@require_GET
def course_one(request, id):
    course = Course.objects.filter(id=id).values().first()
    return CustomerUtil.response_json({
        'code': ResponseCode.BUSINESS_SUCCESS,
        "course": course
    })


def course_list(request):
    courses = list(Course.objects.all().values().order_by('-id'))
    return CustomerUtil.response_json({
        'code': ResponseCode.BUSINESS_SUCCESS,
        "courses": courses
    })
